
package com.kweative.model;

import com.kweative.model.exception.StructureException;
import com.kweative.model.data.DataProvider;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author henrik
 */
abstract public class Schema {
    private String name;
    private LinkedList<Table> tables = new LinkedList<Table>();
    
    public Schema(String name) throws StructureException {
        this.name = name;
        init();
    }
    private void init() {
        makeStructure();
        for(Field f: getClass().getDeclaredFields()) {
            Object t;
            try {
                t = f.get(this);
                if (t instanceof Table)
                    ((Table)t).setSchema(this);
            } catch (Exception ex) {
                Logger.getLogger(Schema.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public Connection getConnection() {
        return DataProvider.connection();
    }

	public String getName() {
		return name;
	}

    public void addTable(Table tbl) {
        tables.add(tbl);
    }

    public LinkedList<Table> getTables() {
        return tables;
    }
    public void update() throws SQLException, StructureException {
        String sql = DataProvider.getInstance().serializeSchema(this);
        for(String stmt:sql.split(";")) {
            if (stmt.trim().length() == 0) continue;
            getConnection().createStatement().execute(stmt.trim());
        }
    }
    
	
    abstract protected void makeStructure();
}
